package com.alkin.thing.project.alkin;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;

/**
 * @Author:jack
 * @Description:
 * @Date: Created in  2020/06/02
 * @Modified By:
 */
public class LogInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        String method = request.getMethod();
        StringBuffer buffer = new StringBuffer();
        buffer.append("\n");
        buffer.append("[preHandle] request uri ->").append(url).append("\n");
        buffer.append("[preHandle] request method ->").append(method).append("\n");

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String name = (String)headerNames.nextElement();
            String value = request.getHeader(name);
            buffer.append("[preHandle] request header ->").append(name).append(":").append(value).append("\n");
        }
        Map<String,String[]> map = request.getParameterMap();
        for(String key : map.keySet()){
            buffer.append("[preHandle] request paras ->").append(key).append(":[");
            String[] strs = map.get(key);
            for(int i = 0 ; i < strs.length ; i++){
                buffer.append(strs[i]);
                if(i != strs.length -1){
                    buffer.append(",");
                }
            }
            buffer.append("]").append("\n");
        }
        logger.info( buffer.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
